import { NavBar, TextArea, Button, Image } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { useState, useEffect } from 'react'
import MsgLeft from './components/MsgLeft'
import MsgRight from './components/MsgRight'
import { useSocket } from '../../hooks'
import styles from './css/chat.module.css'
function Chat() {
  const nav = useNavigate()
  // 响应式状态：用户在聊天区输入的文本内容
  const [value, setValue] = useState('')
  // 存储聊天的消息
  const [list, setList] = useState([])
  const [emit] = useSocket('wss://api-ticket.liulongbin.top', (msg) => {
    const obj = { type: 'AI', msg: msg.replaceAll('{br}', '<br/>') }
    setList((prev) => [...prev, obj])
  })
  // 发送消息给服务器
  function sendMsg() {
    if (!value) return
    // TODO: 把 Hook 返回的 emit 方法进行调用，从而向服务器发消息
    emit(value)
    setList((prev) => [...prev, { type: 'Me', msg: value }])
    setValue('')
  }
  useEffect(() => {
    const dom = document.querySelector('#box')
    const last = dom.lastElementChild
    if (last) {
      last.scrollIntoView({
        behavior: 'smooth',
        block: 'end'
      })
    }
  }, [list])
  return (
    <div className={styles.box}>
      {/* 顶部导航栏 */}
      <NavBar
        onBack={() => nav(-1)}
        className={styles.top}
      >
        在线客服
      </NavBar>
      {/* 聊天区的内容 */}
      <div
        className={styles.middle}
        id="box"
      >
        {list.map((item, i) =>
          item.type === 'AI' ? (
            <MsgLeft
              key={i}
              msg={item.msg}
            />
          ) : (
            <MsgRight
              key={i}
              content={item.msg}
            />
          )
        )}
      </div>
      {/* 消息发送区 */}
      <div className={styles.bottom}>
        {/* 文本框 */}
        <TextArea
          placeholder="请输入聊天内容"
          value={value}
          onChange={(val) => setValue(val.trim())}
          onEnterPress={sendMsg}
        />
        {/* 发送按钮 */}
        <Button
          color="primary"
          fill="solid"
          disabled={value.length === 0}
          onClick={sendMsg}
        >
          发送
        </Button>
      </div>
    </div>
  )
}
export default Chat